package com.maixun.lib_base.observer

import com.maixun.lib_network.entity.NetBaseEntity
import com.maixun.lib_base.ServerCode
import com.maixun.lib_base.mvp.BaseContract
import io.reactivex.Observer
import io.reactivex.disposables.Disposable

/**
 * 作者：Lmoumou
 * 时间：2020/7/15 11:17
 */
abstract class NetBaseObserver<T>(
    private val mView: BaseContract.BaseView,
    private val mPresenter: BaseContract.BasePresenter
) : Observer<NetBaseEntity<T>> {
    override fun onComplete() {

    }

    override fun onSubscribe(d: Disposable) {
        mPresenter.addDisposable(d)
    }

    override fun onNext(t: NetBaseEntity<T>) {
        try {
            when (t.resCode) {
                ServerCode.SUCCESS -> {
                    onSuccess(t.result)
                }
                else -> {
                    onFail(t.errMsg)
                    mView.onServerCode(t.errMsg, t.resCode)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mView.onDataAnalyzeEx(e)
        }
    }

    override fun onError(e: Throwable) {
        mView.onNetEx(e)
    }

    abstract fun onSuccess(t: T?)
    abstract fun onFail(msg: String?)
}